from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from user.models import User, VSession, WarZone, Company
from storehouse.models import Storehouse, StorehouseConnect
from log.models import UserLog, StoreHouseLog
from user.dataCheck import DataCheck
import pdb, os, requests, json

import logging
from software.views.view_download import download
from conf.sysConfig import config

tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")

datacheck = DataCheck()


def storehouseAdd(request, *args, **kwargs):
    """
        url    : /storehouse/add/
        method : POST

    :param request:
              token: data.token, // 用户秘钥
              storehouseName: data.storehouseName  //仓库名称
              storehouseDetails: data.storehouseDetails  //仓库描述
              storehouseType: data.storehouseType  //仓库类型              
              warZoneId: data.warZoneId  //所属战区
              companyId: data.companyId  //所属单位          

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    warZone = WarZone.objects.get(pk=requestParam['warZoneId'])
    company = Company.objects.get(pk=requestParam['companyId'])
    # pdb.set_trace()
    # user = datacheck.getUser(requestParam['token'])
    storehouse = Storehouse.objects.filter(storehouseName=requestParam['storehouseName'])
    if storehouse.exists():
        pass
    else:
        storehouse = Storehouse.objects.create(
            # user = user,
            storehouseName=requestParam['storehouseName'],
            storehouseDetails=requestParam['storehouseDetails'],
            storehouseType=requestParam['storehouseType'],
            storeIP=requestParam['storeIP'],
            storePort=requestParam['storePort'],
            linkName=requestParam['linkName'],
            linkPhone=requestParam['linkPhone'],
            warZone=warZone,
            company=company,
        )

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


# def getIPList(request, *args, **kwargs):
#     """
#         url    : /storehouse/IPget/
#         method : POST

#     :param request:
#                token: data.token, // 用户的秘钥
#                page: data.page,
#                maxItem: data.maxItem

#     :return:
#                 'code': null, // 标志返回状态、0：成功 1：失败
#                 'msg': null, // 返回消息
#                 'totalNum': null, // 总条数
#                 'IPList':[{
#                     'storehouseIdId': null, //仓库ID
#                     'storeIP': null, //IP
#                 }]
#     """

#     form = request.checkForm
#     requestParam = form.cleaned_data

#     user = datacheck.getUser(requestParam['token'])
#     userType = user.userType

#     if userType == '仓库管理人员':
#         IPList = Storehouse.objects.filter(isMasterStore=True)
#         totalNum = len(IPList)
#         IPLists = []
#         result = IPList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
#                                                                                                 requestParam['page'] *
#                                                                                                 requestParam['maxItem'])]


#         for storehouse in result:

#             IPList = {
#                 'storehouseId': storehouse.id,
#                 'storeIP': storehouse.storeIP ,
#             }
#             IPLists.append(IPList)

#     else:
#         data = {
#             'code': 1,
#             'msg': 'userType error',
#         }

#         return JsonResponse(data)


#     data = {
#         "code": 0,
#         "msg": "success",
#         "totalNum": totalNum,
#         "IPList": IPLists,
#     }
#     return JsonResponse(data)


def IPChange(request, *args, **kwargs):
    """
        url    : /storehouse/IPchange/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
                storeIP:data.storeIP,//仓库id


    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
    """
    # pdb.set_trace()
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    if requestParam['token'] != '':
        user = datacheck.getUser(requestParam['token'])
        userType = user.userType

        storehouse = Storehouse.objects.filter(user=user).first()
        storehouseInfo = {
            "storehouseName": storehouse.storehouseName,
            "storehouseDetails": storehouse.storehouseDetails,
            "storeIP": storehouse.storeIP,
            "warZone": storehouse.warZone.name,
            "company": storehouse.company.name,
            "linkName": storehouse.linkName,
            "linkPhone": storehouse.linkPhone,
            'storePort': storehouse.storePort,
        }
        if userType == '2':
            if requestParam['isMasterStore'] == '' and requestParam['connectIP'] != '' and requestParam[
                'connectPort'] != '':
                if storehouse.connectState == '0' or storehouse.connectState == '3':
                    # 未连接
                    filterDict = {}
                    filterDict['connectIP'] = requestParam['connectIP']
                    filterDict['connectPort'] = requestParam['connectPort']
                    dataINfo = dict(storehouseInfo, **filterDict)
                    data1 = requests.post("http://" + requestParam['connectIP'] + ":" + requestParam[
                        'connectPort'] + "/api/storehouse/" + 'IPchange/', data=dataINfo)
                    data = json.loads(data1.text)
                    if data.get('msg') == 'success':
                        storehouse.connectIP = requestParam['connectIP']
                        storehouse.connectPort = requestParam['connectPort']
                        storehouse.connectState = 1
                        storehouse.save()
                        option = '申请连接主节点IP为：' + str(requestParam['connectIP']) + ':' + str(requestParam['connectPort'])
                        log = StoreHouseLog.objects.create(
                            user=user,
                            storeHouse=storehouse,
                            operate=option,
                        )
                    return JsonResponse(data)
                elif storehouse.connectState == '2':
                    ##已连接到一个主仓库
                    filterDict = {}
                    filterDict['connectIP'] = requestParam['connectIP']
                    filterDict['connectPort'] = requestParam['connectPort']
                    ##请求新仓库连接
                    dataINfo = dict(storehouseInfo, **filterDict)
                    data1 = requests.post("http://" + requestParam['connectIP'] + ":" + requestParam[
                        'connectPort'] + "/api/storehouse/" + 'IPchange/', data=dataINfo)
                    data = json.loads(data1.text)
                    ##原仓库断开连接
                    request = {}
                    request['msg'] = 'change'
                    requestINfo = dict(storehouseInfo, **request)
                    data2 = requests.post(
                        "http://" + storehouse.connectIP + ":" + storehouse.connectPort + "/api/storehouse/" + 'IPchange/',
                        data=requestINfo)
                    data3 = json.loads(data2.text)
                    if data.get('msg') == 'success' and data3.get('msg') == 'success':
                        storehouse.connectIP = requestParam['connectIP']
                        storehouse.connectPort = requestParam['connectPort']
                        storehouse.connectState = 1
                        storehouse.save()
                        option = '申请连接主节点IP为：' + str(requestParam['connectIP']) + ':' + str(requestParam['connectPort'])
                        log = StoreHouseLog.objects.create(
                            user=user,
                            storeHouse=storehouse,
                            operate=option,
                        )
                    return JsonResponse(data)
            elif requestParam['isMasterStore'] != '' and requestParam['connectIP'] == '':
                if requestParam['isMasterStore'] == '1' and storehouse.isMasterStore == False:
                    if storehouse.connectState == '1' or storehouse.connectState == '2':
                        ##连接到某一主仓库
                        filterDict = {}
                        filterDict['isMasterStore'] = requestParam['isMasterStore']
                        dataINfo = dict(storehouseInfo, **filterDict)
                        data1 = requests.post(
                            "http://" + storehouse.connectIP + ":" + storehouse.connectPort + "/api/storehouse/" + 'IPchange/',
                            data=dataINfo)
                        data = json.loads(data1.text)
                        if data.get('msg') == 'success':
                            storehouse.connectState = 0
                            storehouse.storeIPType = 1
                            storehouse.isMasterStore = True
                            storehouse.connectIP = ''
                            storehouse.connectPort = ''
                            storehouse.save()
                            option = '更换为主仓库'
                            log = StoreHouseLog.objects.create(
                                user=user,
                                storeHouse=storehouse,
                                operate=option,
                            )
                            return JsonResponse(data)
                        else:
                            data = {
                                'code': 0,
                                'msg': 'error error',
                            }
                            logger_request.info(data)
                            return JsonResponse(data)
                    else:
                        ##未连接
                        storehouse.storeIPType = 1
                        storehouse.isMasterStore = True
                        storehouse.connectIP = ''
                        storehouse.connectPort = ''
                        storehouse.save()
                        option = '更换为主仓库'
                        log = StoreHouseLog.objects.create(
                            user=user,
                            storeHouse=storehouse,
                            operate=option,
                        )
                elif requestParam['isMasterStore'] == '0' and storehouse.isMasterStore == True:
                    storehouse.connectState = 0
                    storehouse.storeIPType = 0
                    storehouse.isMasterStore = False
                    storehouse.save()
                    option = '更换为子仓库'
                    log = StoreHouseLog.objects.create(
                        user=user,
                        storeHouse=storehouse,
                        operate=option,
                    )
        else:
            data = {
                'code': 0,
                'msg': 'userType error',
            }
            logger_request.info(data)
            return JsonResponse(data)
    elif requestParam['token'] == '':
        # 为二次转发请求
        subStorehouseItem = Storehouse.objects.filter(storehouseName=requestParam['storehouseName'],
                                                      storeIP=requestParam['storeIP'])
        if subStorehouseItem.exists():
            subStorehouse = subStorehouseItem[0]
            subStorehouse.connectState = 1
            subStorehouse.save()
        else:
            warZone = WarZone.objects.filter(name=requestParam['warZone']).first()
            company = Company.objects.filter(name=requestParam['company'], warZone=warZone).first()
            subStorehouse = Storehouse.objects.create(
                # user = user,
                storehouseName=requestParam['storehouseName'],
                storehouseDetails=requestParam['storehouseDetails'],
                storeIP=requestParam['storeIP'],
                storePort=requestParam['storePort'],
                linkName=requestParam['linkName'],
                linkPhone=requestParam['linkPhone'],
                connectState=1,
                warZone=warZone,
                company=company,
            )
        if requestParam['isMasterStore'] == '' and requestParam['connectIP'] != '' and requestParam[
            'connectPort'] != '':
            # 子仓库申请连接
            masterStorehouse = Storehouse.objects.filter(storeIP=requestParam['connectIP'],
                                                         storePort=requestParam['connectPort']).first()
            if masterStorehouse.isMasterStore == True:
                storehouseConnect = StorehouseConnect.objects.create(
                    masterStorehouseId=masterStorehouse.id,
                    subStorehouseId=subStorehouse.id,
                    storehouse=masterStorehouse,
                )
            else:
                data = {
                    'code': 0,
                    'msg': 'store not master',
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['isMasterStore'] != '':
            # 变更仓库类型请求
            if requestParam['isMasterStore'] == '1':
                storehouseConnect = StorehouseConnect.objects.filter(subStorehouseId=subStorehouse.id)
                storehouseConnect.delete()
                subStorehouse.connectState = 0
                subStorehouse.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'master change error ',
                }
                logger_request.info(data)
                return JsonResponse(data)
        elif requestParam['msg'] != '':
            # 更换节点请求
            if requestParam['msg'] == 'change':
                storehouseConnect = StorehouseConnect.objects.filter(subStorehouseId=subStorehouse.id)
                storehouseConnect.delete()
                subStorehouse.connectState = 0
                subStorehouse.save()
            else:
                data = {
                    'code': 0,
                    'msg': 'msg error',
                }
                logger_request.info(data)
                return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def getWarZoneList(request, *args, **kwargs):
    """
        url    : /storehouse/warzone/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'warZoneList':[{
                    'warZoneId':null,//战区id
                    'name':null,//战区名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    warZoneList = WarZone.objects.filter(isActive=True, warzoneState='1')
    if warZoneList.exists():
        totalNum = len(warZoneList)
        warZoneLists = []
        result = warZoneList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

        for warZone in result:
            warZoneList = {
                'warZoneId': warZone.id,
                'name': warZone.name,
            }
            warZoneLists.append(warZoneList)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "warZonelist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "warZonelist": warZoneLists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def getCompanyList(request, *args, **kwargs):
    """
        url    : /storehouse/company/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
               page: data.page,
               maxItem: data.maxItem
               warZoneId: data.warZoneId,

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'companyList':[{
                    'companyId':null,//单位id
                    'name':null,//单位名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    companyList = Company.objects.filter(warZone=requestParam['warZoneId'], isActive=True, companyState='1')
    if companyList.exists():
        totalNum = len(companyList)
        companyLists = []
        result = companyList[min(totalNum, (requestParam['page'] - 1) * requestParam['maxItem']): min(totalNum,
                                                                                                      requestParam[
                                                                                                          'page'] *
                                                                                                      requestParam[
                                                                                                          'maxItem'])]

        for company in result:
            companyList = {
                'companyId': company.id,
                'name': company.name,
            }
            companyLists.append(companyList)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "totalNum": 0,
            "companylist": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "totalNum": totalNum,
        "companylist": companyLists,
    }
    logger_request.info(data)
    return JsonResponse(data)


def storehouseOperation(request, *args, **kwargs):
    """
        url    : /user/operations/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥
                storehouseId:data.storehouseId,//仓库id
                operation: data.operation //0表示开启（接入），1表示禁用，2表示删除,3表示拒绝

    :return:
              'code'         // 标志返回状态、0：成功 1：失败
              'msg'          // 返回消息

    """
    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)
    # pdb.set_trace()    
    if requestParam['token'] != '':
        user = datacheck.getUser(requestParam['token'])
        userType = user.userType
        # pdb.set_trace()
        masterStore = Storehouse.objects.filter(user=user).first()

        if userType == '2' and masterStore.isMasterStore == True:
            storehouse = Storehouse.objects.get(pk=requestParam['storehouseId'])
            storeConnect = StorehouseConnect.objects.filter(subStorehouseId=requestParam['storehouseId'],
                                                            masterStorehouseId=masterStore.id).first()
            # pdb.set_trace()
            if requestParam['operation'] == '0' and storeConnect.isConnect == False:
                storeConnect.isConnect = True
                storeConnect.connectState = 2
                storeConnect.save()
                storehouse.connectState = 2
                storehouse.save()
                option = '允许' + str(storehouse.storehouseName) + '接入'
                log = StoreHouseLog.objects.create(
                    user=user,
                    storeHouse=masterStore,
                    operate=option,
                )
                filterDict = {}
                filterDict['operation'] = requestParam['operation']
                filterDict['storeIP'] = storehouse.storeIP
                filterDict['storePort'] = storehouse.storePort
                filterDict['storehouseName'] = storehouse.storehouseName
                data1 = requests.post(
                    "http://" + storehouse.storeIP + ":" + storehouse.storePort + "/api/storehouse/" + 'operations/',
                    data=filterDict)
                data = json.loads(data1.text)
                return JsonResponse(data)
            elif requestParam['operation'] == '0' and storeConnect.isConnect == True and storehouse.isOpen == False:
                storehouse.isOpen = True
                storehouse.storehouseState = 0
                storehouse.save()
            elif requestParam['operation'] == '1' and storeConnect.isConnect == True and storehouse.isOpen == True:
                storehouse.isOpen = False
                storehouse.storehouseState = 1
                storehouse.save()
            elif requestParam['operation'] == '2' and storeConnect.isConnect == True and storehouse.isActive == True:
                filterDict = {}
                filterDict['operation'] = requestParam['operation']
                filterDict['storeIP'] = storehouse.storeIP
                filterDict['storePort'] = storehouse.storePort
                filterDict['storehouseName'] = storehouse.storehouseName
                data1 = requests.post(
                    "http://" + storehouse.storeIP + ":" + storehouse.storePort + "/api/storehouse/" + 'operations/',
                    data=filterDict)
                data = json.loads(data1.text)
                storeConnect.delete()
                storehouse.connectIP = ''
                storehouse.connectState = 0
                storehouse.save()
                return JsonResponse(data)
            elif requestParam['operation'] == '3' and storeConnect.isConnect == False:
                storeConnect.isConnect = False
                storeConnect.connectState = 3
                storeConnect.save()
                storehouse.connectState = 3
                storehouse.save()
                option = '拒绝' + str(storehouse.storehouseName) + '接入'
                log = StoreHouseLog.objects.create(
                    user=user,
                    storeHouse=masterStore,
                    operate=option,
                )
                filterDict = {}
                filterDict['operation'] = requestParam['operation']
                filterDict['storeIP'] = storehouse.storeIP
                filterDict['storePort'] = storehouse.storePort
                filterDict['storehouseName'] = storehouse.storehouseName
                data1 = requests.post(
                    "http://" + storehouse.storeIP + ":" + storehouse.storePort + "/api/storehouse/" + 'operations/',
                    data=filterDict)
                data = json.loads(data1.text)
                return JsonResponse(data)
            else:
                data = {
                    'code': 0,
                    'msg': 'operation error',
                }
                logger_request.info(data)
                return JsonResponse(data)

        else:
            data = {
                'code': 0,
                'msg': 'userType error',
            }
            logger_request.info(data)
            return JsonResponse(data)

    if requestParam['token'] == '':
        # 二次请求子仓库
        storehouse = Storehouse.objects.get(storehouseName=requestParam['storehouseName'],
                                            storeIP=requestParam['storeIP'], storePort=requestParam['storePort'])
        # pdb.set_trace()
        if requestParam['operation'] == '0':
            storehouse.connectState = 2
            storehouse.save()
        elif requestParam['operation'] == '2' and storehouse.connectState == '2':
            storehouse.connectIP = ''
            storehouse.connectPort = ''
            storehouse.connectState = 0
            storehouse.save()
        elif requestParam['operation'] == '3' and storehouse.connectState == '1':
            storehouse.connectState = 3
            storehouse.save()
        else:
            data = {
                'code': 0,
                'msg': 'operation error',
            }
            logger_request.info(data)
            return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
    }
    logger_request.info(data)
    return JsonResponse(data)


def getSelect(request, *args, **kwargs):
    """
        url    : /storehouse/getselect/
        method : POST

    :param request:
               token: data.token, // 用户的秘钥

    :return:
                'code': null, // 标志返回状态、0：成功 1：失败
                'msg': null, // 返回消息
                'totalNum': null, // 总条数
                'companyList':[{
                    'companyId':null,//单位id
                    'name':null,//单位名称
                }]
    """

    form = request.checkForm
    requestParam = form.cleaned_data
    logger_request.info(requestParam)

    warZoneList = WarZone.objects.filter(isActive=True)
    if warZoneList.exists():
        warZoneLists = []

        for warZone in warZoneList:
            companyList = Company.objects.filter(warZone=warZone, isActive=True)
            if companyList.exists():
                companyLists = []
                for company in companyList:
                    companyList = {
                        'id': company.id,
                        'label': company.name,
                    }
                    companyLists.append(companyList)

                warZoneList = {
                    'id': warZone.id,
                    'label': warZone.name,
                    'children': companyLists,
                }
                warZoneLists.append(warZoneList)
    else:

        data = {
            'code': 0,
            'msg': 'not exist',
            "options": [],
        }
        logger_request.info(data)
        return JsonResponse(data)

    data = {
        "code": 0,
        "msg": "success",
        "options": warZoneLists,
    }
    logger_request.info(data)
    return JsonResponse(data)
